<template>
  <view class="container">
    <view class="smart-form">
      <uni-forms ref="formRef" :label-width="100" :modelValue="form" label-position="left" :rules="rules">
        <view class="smart-form-group">
          <view class="smart-form-group-content">
            <uni-forms-item class="smart-form-item" label="企业名称：" name="enterpriseName" required>
              <uni-easyinput type="input" trim="all" v-model="form.enterpriseName" placeholder="请输入" class="rounded-input" />
            </uni-forms-item>
            <!--            <uni-forms-item class="smart-form-item" label="企业logo：" name="enterpriseLogo" required>
                          <uni-file-picker
                            limit="1"
                            @delete="onDeleteEnterpriseLogoFile"
                            v-model="enterpriseLogoFile"
                            @select="onSelectEnterpriseLogoFile"
                          ></uni-file-picker>
                        </uni-forms-item>-->

            <uni-forms-item class="smart-form-item" label="统一社会信用代码：" name="unifiedSocialCreditCode" required>
              <uni-easyinput type="input" trim="all" v-model="form.unifiedSocialCreditCode" placeholder="请输入" class="rounded-input" />
            </uni-forms-item>
            <uni-forms-item class="smart-form-item" label="联系人：" name="contact" required>
              <uni-easyinput type="input" trim="all" v-model="form.contact" placeholder="请输入" class="rounded-input" />
            </uni-forms-item>
            <uni-forms-item class="smart-form-item" label="联系人电话：" name="contactPhone" required>
              <uni-easyinput type="input" trim="all" v-model="form.contactPhone" placeholder="请输入" class="rounded-input" />
            </uni-forms-item>
            <uni-forms-item class="smart-form-item" label="所在城市：" name="formProvince" required>
              <uni-data-picker v-model="areas" :localdata="Areas" popup-title="请选择" @change="onchange"/>
            </uni-forms-item>
            <uni-forms-item class="smart-form-item" label="详细地址：" name="address" required>
              <uni-easyinput type="input" trim="all" v-model="form.address" placeholder="请输入" class="rounded-input" />
            </uni-forms-item>
            <uni-forms-item class="smart-form-item" label="邮箱：" name="email" required>
              <uni-easyinput type="input" trim="all" v-model="form.email" placeholder="请输入" class="rounded-input" />
            </uni-forms-item>
            <uni-forms-item class="smart-form-item" label="营业执照：" name="businessLicense" required>
              <uni-file-picker
                  limit="1"
                  @delete="onDeleteBusinessLicenseFile"
                  v-model="businessLicenseFile"
                  @select="onSelectBusinessLicenseFile"
                  class="rounded-input"
              />
            </uni-forms-item>
          </view>
        </view>
      </uni-forms>

      <view class="smart-form-submit fixed-bottom-button">
        <button class="smart-form-submit-btn" type="default" @click="cancel">取消</button>
        <button class="smart-form-submit-btn" type="primary" @click="submit">保存</button>
      </view>
    </view>
  </view>
</template>


<script setup>
import {reactive, ref} from 'vue';
import {enterpriseApi} from '@/api/business/oa/enterprise-api';
import {smartSentry} from '@/lib/smart-sentry';
import {SmartLoading, SmartToast} from '@/lib/smart-support';
import {fileApi} from '@/api/support/file-api';
import {FILE_FOLDER_TYPE_ENUM} from '@/constants/support/file-const';
import _ from 'lodash';
import {PROVINCE_CITY_DISTRICT} from './PROVINCE_CITY_DISTRICT'
import UniDataPicker from "@/uni_modules/uni-data-picker/components/uni-data-picker/uni-data-picker.vue";

// --------------------- 表单 ---------------------

const defaultFormData = {
  enterpriseId: undefined,
  enterpriseName: undefined,
  unifiedSocialCreditCode: undefined,
  businessLicense: [],
  contact: undefined,
  enterpriseLogo: [],
  contactPhone: undefined,
  email: undefined,
  province: undefined,
  provinceName: undefined,
  city: undefined,
  cityName: undefined,
  district: undefined,
  districtName: undefined,
  address: undefined,
  disabledFlag: false,
  blacklistFlag: false,
};
let form = reactive({...defaultFormData});
const Areas = ref(PROVINCE_CITY_DISTRICT)
const enterpriseLogoFile = ref([]);
const businessLicenseFile = ref([]);
const areas = ref([])

const rules = {
  enterpriseName: {
    rules: [{required: true, errorMessage: '请输入'}],
  },
  enterpriseLogo: {
    rules: [{required: true, errorMessage: '请上传'}]
  },
  businessLicense: {
    rules: [{required: true, errorMessage: '请上传'}],
  },
  unifiedSocialCreditCode: {
    rules: [{required: true, errorMessage: '请输入'}],
  },
  contact: {
    rules: [{required: true, errorMessage: '请输入'}],
  },
  contactPhone: {
    rules: [{
      required: true, errorMessage: '请输入', validateFunction: function (rule, value, data, callback) {
        if (!/^1\d{10}$/.test(value)) {
          callback('手机号格式不正确')
        }
        return true
      }
    }],
  },
  formProvince: {
    rules: [{required: true, errorMessage: '请选择'}],
  },
  address: {
    rules: [{required: true, errorMessage: '请输入'}],
  },
  email: {
    rules: [{
      required: true, errorMessage: '请输入', validateFunction: function (rule, value, data, callback) {
        if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(value)) {
          callback('邮箱格式不正确')
        }
        return true
      }
    }],
  }
};


// --------------------- 文件 ---------------------
function onSelectEnterpriseLogoFile(param) {
  let tempFilePaths = param.tempFilePaths;
  for (const tempFilePath of tempFilePaths) {
    upload(tempFilePath, 'enterpriseLogo');
  }
}

function onSelectBusinessLicenseFile(param) {
  let tempFilePaths = param.tempFilePaths;
  for (const tempFilePath of tempFilePaths) {
    upload(tempFilePath, 'businessLicense');
  }
}

async function upload(tempFilePath, key) {
  try {
    SmartLoading.show();
    let res = await fileApi.upload(tempFilePath, FILE_FOLDER_TYPE_ENUM.FEEDBACK.value);
    res.data.tempFilePath = tempFilePath;
    form[key].push(res.data);
  } catch (e) {
    smartSentry.captureError(e);
  } finally {
    SmartLoading.hide();
  }
}

function onDeleteEnterpriseLogoFile(param) {
  if (!param.tempFilePath) {
    return;
  }
  _.remove(form.enterpriseLogo, (e) => e.tempFilePath === param.tempFilePath);
}

function onDeleteBusinessLicenseFile(param) {
  if (!param.tempFilePath) {
    return;
  }
  _.remove(form.businessLicense, (e) => e.tempFilePath === param.tempFilePath);
}

function onchange(e) {
  const [province = {}, city = {}, district = {}] = e.detail.value
  form.province = province.value
  form.provinceName = province.text
  form.city = city.value
  form.cityName = city.text
  form.district = district.value
  form.districtName = district.text
  //
  form.formProvince = province.value
}

// ----------------------- 表单操作 ------------------------

const formRef = ref();

// 取消
function cancel() {
  uni.navigateBack();
}

// 确定
function submit() {
  formRef.value
      .validate()
      .then(async () => {
        SmartLoading.show();
        try {
          form.disabledFlag = false
          form.blacklistFlag = false
          await enterpriseApi.create(form);
          SmartToast.success('提交成功');
          uni.navigateBack();
        } catch (error) {
          smartSentry.captureError(error);
        } finally {
          SmartLoading.hide();
        }
      })
      .catch((error) => {
        console.log('error', error);
        // SmartToast.toast('参数验证错误，请仔细填写表单数据!');
      });
}
</script>

<style lang="scss" scoped>
@import '@/theme/register.scss';
</style>
